<?php

namespace App\Models\Ddaman;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\common\Base;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class WorkflowLeave extends Base
{
    use HasFactory;

    protected $table = "workflow_leave";

    //const CREATED_AT = null;
    //const UPDATED_AT = null;

    protected $fillable = [
        'guid','wid','leave_type','uid','reason','applicant','branch','branch_id'
    ];


    public $rule = [
        'name' => 'required|string|between:2,100',
        'logo' => 'required',
    ];

    public $editRule = [
        'id' => 'required',
        'name' => 'required|string|between:2,100',
        'logo' => 'required',
    ];

    public $message = [
        'id.required' => '标识必须',
        'name.required' => '分类名称必须填写',
        'logo.required'=>"请上传品牌logo",
    ];

    /*
     * 获取列表
     * */
    public function getList( $param = [] )
    {
        $limit = isset($param['limit']) ? $param['limit'] : 10;
        $where = [];

        if (isset($param['keywords']) && $param['keywords']){
            $keywords = trim($param['keywords']);
            $where[] = ['name','like',"%$keywords%"];
        }

        $field = array_merge(['id'],$this->fillable);
        $list = $this->where($where)->orderBy('id','desc')->select($field)->paginate($limit);

        return $list;

    }

    /*
     * 申请请假
     * */
    public function changes( $data )
    {
        $data['uid'] = get_uuid();
        //dump($data);die;
        $lData = stayFill($this->fillable,$data);
        $info = $this->where('wid',$lData['wid'])->first();
        if ($info){
            $result = $this->where('id',$info->id)->update($lData);
            $data['leave_id'] = $info->guid;
        }else{
            $guid = getGuid();
            $lData['guid'] = $guid;
            $result = $this->create($lData);
            $data['leave_id'] = $guid;
        }
        if (!$result){
            $this->error = "更新失败";
            return false;
        }

        //保存请假时间
        $model = new WorkflowLeaveDate();
        $result = $model->changes($data);
        if (!$result){
            $this->error = $model->getError();
            return false;
        }

        return true;
    }


    /*
     * 获取请假类型
     * */
    public function getLeveType()
    {
        $list = DB::table('workflow_leave_type')
            ->orderBy('sort','asc')
            ->get();
        return $list;
    }


}
